package com.agent.demo;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class DefineTransformer implements ClassFileTransformer {

        @Override
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            if (!className.endsWith("TestService")) {
                return classfileBuffer;
            }
            try {
                ClassReader classReader = new ClassReader(className);
                ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
                ClassVisitor classVisitor = new MyClassVisitor(classWriter);
                classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);
                return classWriter.toByteArray();
            }catch (Exception e){
                e.printStackTrace();
            }
            return classfileBuffer;
        }
    }